package com.unieagle.exam.ui;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.unieagle.exam.R;
import com.unieagle.exam.http.IVolleyListener;
import com.unieagle.exam.http.ResultTipHelper;
import com.unieagle.exam.http.TaskHelper;
import com.unieagle.exam.http.VolleyRequest;
import com.unieagle.exam.http.VolleyTask;
import com.unieagle.exam.model.UserInfoResult;
import com.unieagle.exam.utils.IdentityUtils;
import com.unieagle.exam.utils.SharedPreferenceUtils;


public class RegisterFormFragment extends Fragment implements IVolleyListener{
    private CheckBox mCbIdentityShower;
    private Button mBtSubmit,mBtAlreadyRegister;
    private Input mInName,mInIdentity,mInPhone;
    private OnRegisterListener mOnRegisterListener;

    public interface OnRegisterListener{
        void onRegisterSuccess();
    }

    public void setOnRegisterListener(OnRegisterListener l){
        mOnRegisterListener = l;
    }

    private class Input{
        EditText mEdit;
        TextView mTip;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.register_form_fragment_layout,container,false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mInName = new Input();
        mInName.mEdit = (EditText)view.findViewById(R.id.name);
        mInName.mTip = (TextView)view.findViewById(R.id.name_tip);

        mInIdentity = new Input();
        mInIdentity.mEdit = (EditText)view.findViewById(R.id.identity);
        mInIdentity.mTip = (TextView)view.findViewById(R.id.identity_tip);

        mInPhone = new Input();
        mInPhone.mEdit = (EditText)view.findViewById(R.id.phone);
        mInPhone.mTip = (TextView)view.findViewById(R.id.phone_tip);

        mCbIdentityShower = (CheckBox) view.findViewById(R.id.identity_shower);
        mBtSubmit = (Button) view.findViewById(R.id.register_submit);

        mBtAlreadyRegister = (Button)view.findViewById(R.id.already_register);
        initListener();
    }

    private void initListener(){
        mBtSubmit.setOnClickListener(mSubmitClick);
        mCbIdentityShower.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                int selection = mInIdentity.mEdit.getSelectionEnd();
                mInIdentity.mEdit.setInputType(b?InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_PASSWORD);
                if(selection <0) selection = 0;
                mInIdentity.mEdit.setSelection(selection);
            }
        });
        mCbIdentityShower.setChecked(true);
        mCbIdentityShower.setChecked(false);

        mInName.mEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    dismissTip(mInName);
                }else{
                    noEmptyCheck(mInName);
                }
            }
        });

        mInIdentity.mEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    dismissTip(mInIdentity);
                }else{
                    if(noEmptyCheck(mInIdentity)){
                        if(!IdentityUtils.isValidatedAllIdcard(mInIdentity.mEdit.getText().toString())) {
                            tipError(mInIdentity, "格式不正确");
                        }
                    }
                }
            }
        });

        mInPhone.mEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    dismissTip(mInPhone);
                }else{
                    noEmptyCheck(mInPhone);
                }
            }
        });

        mBtAlreadyRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	startActivity(new Intent(getActivity(),LoginActivity.class));
                getActivity().finish();
            }
        });
    }

    View.OnClickListener mSubmitClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!formCheck()){
                return;
            }
            VolleyTask requestTask = TaskHelper.createRegisterTask(mInName.mEdit.getText().toString(),
            		mInIdentity.mEdit.getText().toString(), 
            		mInPhone.mEdit.getText().toString(), SharedPreferenceUtils.getPushToken(getActivity()));
            requestTask.setVolleyListener(RegisterFormFragment.this);
            VolleyRequest.getInstance().request(requestTask);
            ((BaseActivity)getActivity()).showProgress("注册中");
        }
    };

    @Override
    public void onComplete(VolleyTask task, Object result) {
        String tip = ResultTipHelper.parseResult(result,UserInfoResult.class);
        if(TextUtils.isEmpty(tip)){
        	Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
            if (mOnRegisterListener != null) {
                mOnRegisterListener.onRegisterSuccess();
            }
        }else {
            Toast.makeText(getActivity(), tip, Toast.LENGTH_SHORT).show();
        }
        ((BaseActivity)getActivity()).dismissProgress();
    }

    @Override
    public void onError(VolleyTask task, VolleyError volleyError) {
        Toast.makeText(getActivity(),"注册失败",Toast.LENGTH_SHORT).show();
        ((BaseActivity)getActivity()).dismissProgress();
    }

    private boolean formCheck(){
        if(mInName.mEdit.getText().length() == 0){
            tipError(mInName,"不能为空");
            return false;
        }
        if(mInIdentity.mEdit.getText().length() == 0){
            tipError(mInIdentity,"不能为空");
            return false;
        }else if(!IdentityUtils.isValidatedAllIdcard(mInIdentity.mEdit.getText().toString())){
            tipError(mInIdentity,"格式不正确");
            return false;
        }

        if(mInPhone.mTip.getText().length() == 0){
            tipError(mInPhone,"不能为空");
            return false;
        }
        dismissTip(mInName);
        dismissTip(mInIdentity);
        dismissTip(mInPhone);
        return true;
    }
    private boolean noEmptyCheck(Input tag){
        if(tag.mEdit.getText().length() == 0){
            tipError(tag,"不能为空");
            return false;
        }
        dismissTip(tag);
        return true;
    }

    private void tipError( Input tag,String tip){
        tag.mTip.setText(tip);
        tag.mTip.setVisibility(View.VISIBLE);
        tag.mEdit.setActivated(true);
    }

    private void dismissTip(Input tag){
        tag.mTip.setVisibility(View.GONE);
        tag.mEdit.setActivated(false);
    }
}
